<?php namespace App\Services;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class WxDecryptDataService
{
    const ERROR_CODE_OK = 0;
    const ERROR_CODE_ILLEGAL_ASEKEY = -41001;
    const ERROR_CODE_ILLEGAL_IV = -41002;
    const ERROR_CODE_ILLEGAL_BUFFER = -41003;
    const ERROR_CODE_DECODE_BASE64_ERROR = -41004;

    private $appid;
    private $sessionKey;

    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     * @param $appid string 小程序的appid
     * @param $sessionKey string 用户在小程序登录后获取的会话密钥
     *
     * @return array ['errorCode' : 0, 'data' : '***']
     */
    public function decryptData($appid, $sessionKey, $encryptedData, $iv)
    {
        $this->sessionKey = $sessionKey;
        $this->appid = $appid;

        if (strlen($this->sessionKey) != 24) {
            return ['errorCode' => self::ERROR_CODE_ILLEGAL_ASEKEY];
        }
        $aesKey = base64_decode($this->sessionKey);


        if (strlen($iv) != 24) {
            return ['errorCode' => self::ERROR_CODE_ILLEGAL_IV];
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            return ['errorCode' => self::ERROR_CODE_ILLEGAL_BUFFER];
        }
        if ($dataObj->watermark->appid != $this->appid) {
            return ['errorCode' => self::ERROR_CODE_ILLEGAL_BUFFER];
        }
        $data = $result;
        return [
            'errorCode' => self::ERROR_CODE_OK,
            'data' => $data
        ];
    }
}
